<?php

header("Content-type: text/html; charset=utf-8");

//获取$_GET或$_POST值
function getGP($var, $method = 'GP', $type = 'string') {
    $val;
    if ($method == 'G') {
        $val = isset($_GET[$var]) ? $_GET[$var] : '';
    } elseif ($method == 'P') {
        $val = isset($_POST[$var]) ? $_POST[$var] : '';
    } else {
        $val = isset($_GET[$var]) ? $_GET[$var] : ($_POST[$var] ? $_POST[$var] : '');
    }
    $val = trim($val);
    return ($type == 'string' ? (string) $val : intval($val));
}

function alert($msg) {

    echo $msg;
    $args = func_get_args();
    if (!empty($msg)) {
        $alert = 'alert("' . $msg . '");';
    }
    if (count($args) >= 2) {

        if (empty($args[1])) {
            $jumpurl = 'history.back(-1);';
        } else {
            $jumpurl = 'top.location.href = "' . $args[1] . '";';
        }
//    } else {
//        $jumpurl = 'history.back();';
        // }else{
        //$jumpurl = 'history.back(-1);';
    }
    echo '
	<script type="text/javascript">
		' . $alert . '
		' . $jumpurl . '
	</script>
	';

    exit;
}

/*
 * 对话框提示函数
 */

function showmsg($msg, $url = '0', $isparent = 0) {
    $alert = !empty($msg) ? 'alert("' . $msg . '");' : "";
    echo '<script type="text/javascript">' . "\n" . $alert . "\n";
    if ($url == "") {
        echo 'history.back();';
    } elseif ($url != '1') {
        if (!preg_match('#^https?://#i', $url)) {
            $url = $url;
        }
        if ($isparent == 1) {
            echo 'parent.window.location.href = "' . $url . '";';
        } else {
            echo 'window.location.href = "' . $url . '";';
        }
    }
    echo '</script>';
    exit;
}

function gb2utf8($str) {

    if (empty($str))
        return $str;

    return iconv('gbk//ignore', 'utf-8', $str);

    if (function_exists('iconv')) {
        return iconv('gbk//ignore', 'utf-8', $str);
    }

    if (function_exists('mb_convert_encoding')) {
        return mb_convert_encoding($str, 'gbk', 'utf-8');
    }
}

//UTF-8 转GB编码

function utf82gb($utfstr) {

    if (function_exists('iconv')) {
        return iconv('utf-8', 'gbk//ignore', $utfstr);
    }

    if (function_exists('mb_convert_encoding')) {
        return mb_convert_encoding($utfstr, 'utf-8', 'gbk');
    }
}

function redirect($url) {
    echo "<script>window.location.href='" . $url . "';</script>";
    exit;
}

/**

  +----------------------------------------------------------
 * 说明：重新封装两个数据库查询函数
 * 实现：查询数据，放入到二维数组中
 * 生成日期:2011-3-9
 * 生成人：lrli 349793000
 * 最后修改日期:2010-3-10
 * 最后修改人：lrli 349793000
  +----------------------------------------------------------
 * @access public
  +----------------------------------------------------------
 * @param sql 要执行的SQL语句
  +----------------------------------------------------------
 * @return 返回查询的结果的二维数据
  +----------------------------------------------------------

 */
function fetch_array($sql) {
    $CI = get_instance();
    $CI->load->database();
    $query = $CI->db->query($sql);
    $temp = array();
    foreach ($query->result_array() as $row) {
        $temp[] = $row;
    }
    return $temp;
}

/**

 * @access public
  +----------------------------------------------------------
 * @param sql 要执行的SQL语句
  +----------------------------------------------------------
 * @return 返回查询的结果的二维数据
  +----------------------------------------------------------

 */
function fetch_count($sql) {
    $CI = get_instance();
    $CI->load->database();
    $query = $CI->db->query($sql);
    return $query->num_rows();
}

/**

  +----------------------------------------------------------
 * 说明：重新封装两个数据库查询函数
 * 实现：查询数据一条记录，放入到一维数组中
 * 生成日期:2011-3-9
 * 生成人：lrli 349793000
 * 最后修改日期:2010-3-10
 * 最后修改人：lrli 349793000
  +----------------------------------------------------------
 * @access public
  +----------------------------------------------------------
 * @param sql 要执行的SQL语句
  +----------------------------------------------------------
 * @return 返回查询的结果的一维数据
  +----------------------------------------------------------
 */
function fetch_one_array($sql) {
    $CI = get_instance();
    $CI->load->database();
    $query = $CI->db->query($sql);
    $temp = array();
    $temp = $query->first_row('array');
    return $temp;
}

//是否合法Email地址
function is_email($email) {

    if (preg_match('/^[0-9a-z]+[0-9a-z_\.\-]*@[0-9a-z\-]+(\.[a-z]{2,4}){1,2}$/i', $email)) {
        return true;
    }
    return false;
}

/*
 * 检测输入网址的合法性
 */

function checkUrl($weburl) {
    return !ereg("^http(s)*://[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*$", $weburl);
}

//是否合法密码是否符合规则，字母与数字的组合
function is_password($password) {

    if (preg_match('/^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9]{3,}$/', $password)) {
        return true;
    }
    return false;
}

//是否电话号码
function is_mobile($string) {
    if (preg_match("/^(\d{3}-)(\d{8})$|^(\d{4}-)(\d{7})$|^(\d{4}-)(\d{8})$/", $string) || preg_match('/(13[0-9]|15[0-9]|18[0-9]|14[0-9])\d{8}$/', $string)) {
        return TRUE;
    }
    return FALSE;
}

function get_token_name($token) {
    $sql = "select name from token where token='" . $token . "' ";
    $res = fetch_one_array($sql);
    return $res['name'];
}

function getWxToken($token) {
    $CI = get_instance();
    $CI->load->database();
    $sql = "select * from token where token='" . $token . "' and expires_in >'" . (time() - 120) . "' ";
    $num = fetch_count($sql);
    $res = fetch_one_array($sql);
    if ($num > 0) {
        return $res['access_token'];
    } else {

        $sql_open = "select * from token where token = '$token' ";
        $opdata = fetch_one_array($sql_open);
        $wx = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $opdata['appid'] . '&secret=' . $opdata['appsecret']);
        $token_json = json_decode($wx);
        $access_token = $token_json->access_token;
        $sql = "update token set access_token='$access_token',expires_in='" . time() . "' where token='" . $token . "'";
        $query = $CI->db->query($sql);

        $this->db->update("token", array("access_token" => $token_json->access_token, "expires_in" => time()), "token = '$token'");
        return $token_json->access_token;
    }
}

function array_zh($arr) {
    $re_value = array();
    for ($e = 0; $e < count($arr); $e++) {
        $re_arr[$e] = $arr[$e]['id'];
    }
    return $re_arr;
}

function qutiao_array($arr1, $arr2) {
    $re_arr = array();
    $i = 0;
    for ($e = 0; $e < count($arr1); $e++) {
        if (!in_array($arr1[$e], $arr2)) {
            $re_arr[$i] = $arr1[$e];
            $i++;
        }
    }
    return $re_arr;
}

function Loadfile_wx($token, $pid, $sel_type) {

    $sql_file_wx = "select * from content where id='" . $pid . "' and wx_id!='' and ctime>='" . (time() - 259200) . "' ";
    $num = fetch_count($sql_file_wx);
    if ($num > 0) {
        $res = fetch_one_array($sql_file_wx);
        $re_value['errcode'] = 1;
        $re_value['media_id'] = $res['wx_id'];
        $re_value['created_at'] = $res['ctime'];
        $re_value['errmsg'] = "不更新数据";
        return $re_value;
    } else {
        $sql_file = "select * from content where id='" . $pid . "'";
        $res_file = fetch_one_array($sql_file);
        switch ($sel_type) {
            case "5":
                $type = "image";
                break;
            case "6":
                $type = "voice";
                break;
            case "7":
                $type = "video";
                break;
        }
        $wx_token = getWxToken($token);
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$wx_token&type=$type";
        $post_data = array(
            "media" => "@" . $_SERVER['DOCUMENT_ROOT'] . "/bluewechat" . $res_file['file_url']
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        $file_json = json_decode($output);
        print_R($post_data);
        curl_close($ch);
        $re_value['errcode'] = 0;
        $re_value['media_id'] = $file_json->media_id;
        $re_value['created_at'] = $file_json->created_at;
        $re_value['errmsg'] = $file_json->errmsg;

        return $re_value;
    }
}

function is_token($token) {
    //token_type=1表示公众号，２表示订阅号
    $sql = "select * from token where token='" . $token . "' and token_type='1'";
    $num = fetch_count($sql);
    return $num;
}

function arrayRecursive(&$array, $function, $apply_to_keys_also = false) {
    $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
        if ($key != "name") {
            $array[$key] = $value;
        } else {
            if (is_array($value)) {
                arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }
        }

        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}

function dataPost($post_string, $url) {//POST方式提交数据
    $context = array('http' => array('method' => "POST", 'header' => "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) \r\n Accept: */*", 'content' => $post_string));
    $stream_context = stream_context_create($context);
    $data = file_get_contents($url, FALSE, $stream_context);
    return $data;
}

/*
 * 根据数据类型取出不同的数据
 */

function get_log_type($typeres) {
    $re_value = "";
    switch ($typeres['type']) {
        case "2":
            $sql = "select * from news where list_id='" . $typeres['id'] . "'";
            $res = fetch_array($sql);
            $re_value .="单图:";
            foreach ($res as $key => $row) {
                if ($key != 0)
                    $re_value .="<br>";
                $re_value .=$res['url'];
            }
            break;
        case "3":
            $sql = "select * from news where list_id='" . $typeres['id'] . "'";
            $res = fetch_array($sql);
            $re_value .="多图:";
            foreach ($res as $key => $row) {
                if ($key != 0)
                    $re_value .="<br>";
                $re_value .=$res['url'];
            }
            break;
        case "4":
            $sql = "select * from processes where id='" . $typeres['id'] . "'";
            $res = fetch_array($sql);
            foreach ($res as $key => $row) {
                if ($key != 0)
                    $re_value .="<br>";
                $re_value .=$res['name'];
            }
            break;
        case "5":
        case "6":
        case "7":
            $sql = "select * from content where id='" . $typeres['id'] . "'";
            $res = fetch_one_array($sql);
            $re_value = $res['url'];
            break;
    }
    return $re_value;
}

//返回是否置顶的文字
function gettopstr($n) {
    $topres = array(1 => "置顶", 0 => '-');
    return $topres[$n];
}

//返回是否状态的文字
function getstatusstr($n) {
    $status = array(
        1 => '<font color="#0f0">正常</font>',
        0 => '删除',
        2 => '<font color="#666">隐藏</font>',
        3 => '<font color="#333">未审核</font>',
        4 => '<font color="red">未审核不通过</font>'
    );
    return $status[$n];
}

function getstatusstr2($n) {
    $status = array(1 => '<font color="#0f0">上线</font>', 0 => '删除', 2 => '<font color="#666">下线</font>');
    return $status[$n];
}

function getstatusstr3($n) {
    $status = array(
        1 => '<font color="#0f0">通过</font>',
        0 => '删除',
        2 => '<font color="#666">隐藏</font>',
        3 => '<font color="#333">未审核</font>',
        4 => '<font color="red">未审核不通过</font>'
    );
    return $status[$n];
}

/**
 * 导出XLS表格
 * @header    表格头部一维数组
 * @data      表格内容二维数组
 * @filename  文件名
 * @html       0表示直接导出，1表示在html显示
 */
function data_to_excel($header, $data, $filename = '', $html = 0) {
    if (empty($filename))
        $filename = 'excel';
    $charset = "utf8";
    if (!$html) {
        header("Content-type:application/vnd.ms-excel;charset:" . $charset);
        header("Content-Disposition:filename={$filename}.xls");
    }
    $str_header = "";
    foreach ($header as $val)
        $str_header .= "<th>$val</th>";
    $output = '<html xmlns:o="urn:schemas-microsoft-com:office:office"
                xmlns:x="urn:schemas-microsoft-com:office:excel"
                xmlns="http://www.w3.org/TR/REC-html40">
                <html xmlns="http://www.w3.org/1999/xhtml">
                <head>
                <title>' . $header . '</title>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                </head>
                <body>
                <style>
                th {background:#f0f0f0}
                td {font-size:10.0pt;}


                </style>

                <style type="text/css">
                <!--
                td {
                background-color: #FFFFFF;
                padding-top:1px;
                padding-right:1px;
                padding-left:1px;
                mso-ignore:padding;
                color:black;
                font-size:11.0pt;
                font-weight:400;
                font-style:normal;
                text-decoration:none;
                font-family:宋体;
                mso-generic-font-family:auto;
                mso-font-charset:134;
                mso-number-format:"\@"; //关键是这
                text-align:general;
                vertical-align:middle;
                mso-background-source:auto;
                mso-pattern:auto;
                white-space:nowrap;}
                -->
                </style>
                <table cellspacing="1" cellpadding="5" borderColorDark="#ffffff" width="100%"
                bgColor="#ffffff" borderColorLight="#c0c0c0" border="1">
                <tr>
                ' . $str_header . '
                </tr>
                ';
    foreach ($data as $row) {
        $output .= "<tr>\n";
        foreach ($row as $field) {
            $output .= "<td>{$field}</td>";
        }
        $output .= "</tr>\n";
    }
    $output .= "</table>\n";
    $output .= '</body></html>';
    exit($output);
}

//读取品牌账号的管理
function getUserBrandPermission($userid) {
    $ubp = fetch_array("select * from web_userbrand_permission where user_id ='" . $userid . "'");
    $res_array = array();
    foreach ($ubp as $key => $urow) {
        $res_array[] = $urow["brand_id"];
    }
    return $res_array;
}

//保存后台操作流水记录
function saveAdminLog($userid, $type, $forid, $docon) {
    $CI = get_instance();
    $CI->load->database();
    $indata = array(
        'userid' => $userid,
        "type" => $type,
        "forid" => $forid,
        "docon" => $docon,
        "ip" => getIP(),
        "ctime" => date("Y-m-d H:i:s")
    );
    $CI->db->insert('web_admin_log', $indata);
    return true;
}

// 定义一个函数getIP()
function getIP() {
    global $ip;
    if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
    else
        $ip = "Unknow";
    return $ip;
}

//获取对应品牌活动的各状态的数据
function getActivityStatusCount($bid, $status) {
    $res = fetch_one_array("select count(*) as num from web_activity where bid='" . $bid . "' and status='" . $status . "'");
    return $res["num"];
}

//获取对应品牌新品的各状态的数据
function getProductStatusCount($bid, $status) {
    $res = fetch_one_array("select count(*) as num from web_product where bid='" . $bid . "' and status='" . $status . "'");
    return $res["num"];
}

function getwxuser($openid, $field = "") {
    $res = fetch_one_array("select * from web_user_serve where openid='" . $openid . "' or openid_serve ='" . $openid . "' ");

    if ($field) {
        return $res[$field];
    } else {
        return $res;
    }
}

//获取授权回跳地址
function getWxloginBack($id) {
    $res = fetch_one_array("select * from web_wxlogin_back where id='" . $id . "' limit 1");
    if ($res) {
        return $res["url"];
    } else {
        return "/";
    }
}

//获取留资信息
function getliuzi($id, $field = "") {
    $res = fetch_one_array("select * from web_survey_answer_liuzi where id='" . $id . "'  ");

    if ($field) {
        return $res[$field];
    } else {
        return $res;
    }
}

function user_log_save($admin_name, $admin_id, $msg) {
    $CI = get_instance();
    $CI->load->database();
    return $CI->db->insert('admin_log', array("admin_name" => $admin_name, "admin_id" => $admin_id, "msg" => $msg, "logtime" => time()));
}

?>